package com.execjar.pound;

import com.execjar.fun.FunctionParse;
import com.execjar.fun.FunctionPound;
import com.execjar.fun.FunctionSleep;
import com.execjar.utils.CalculUtils;
import com.execjar.utils.TcpToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
public class Pound {

    static FunctionPound<String, String, Integer, byte[]> funcPound = (ip, port, readLen) -> TcpToolUtils.postReAssignByte(ip, Integer.parseInt(port), readLen);
    /*解析读取结果*/
    static FunctionParse<byte[], Integer> funParseRead = (readBytes) -> Optional.ofNullable(readBytes)
            .map(item -> {
                String s = new String(item, StandardCharsets.UTF_8);
                log.info("地磅读取返回[{}]", s);
                return s;
            }).filter(item -> item.length() > 36).map(item -> {
                List<String> collect = Arrays.stream(item.split("\u0003\u0002"))
                        .filter(str -> StringUtils.length(str.trim()) >= 9)
                        .map(str -> StringUtils.substring(str, 2, str.length() - 3))
                        .collect(Collectors.toList());
                //读取到的不是标准，截取2位的第二位
                String parseIntStr = collect.size() >= 2 ? collect.get(1) : "";
                return Integer.parseInt(parseIntStr);
            }).get();
    /**
     * 睡眠间隔|1秒是根据实际情况测试出来的
     */
    static FunctionSleep funSleep = () -> sleep(1, TimeUnit.SECONDS);


    public static void main1(String[] args) {
        EquDTO equDTO = new EquDTO();
        equDTO.setEqpPort("5302").setEqpIp("192.168.50.62");
        equDTO.setData("dd");
        int loopNum = StringUtils.isBlank(equDTO.getData()) ? 1 : 10;
        PoundRead.loopRead(equDTO, loopNum, 8, 2, 2, 50, funcPound, funParseRead, funSleep, CalculUtils::mode);
        System.out.println("计算完成" + equDTO.getResult());


    }

    public static void sleep(long tiem, TimeUnit timeUnit) {
        //Objects.requireNonNull(timeUnit);
        if (Objects.isNull(timeUnit)) {
            timeUnit = TimeUnit.SECONDS;
        }
        try {
            timeUnit.sleep(tiem);
        } catch (InterruptedException e) {
        }
    }
}
